package com.neusoft.hifly.commons.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Title: 核心类库
 * <p>
 * Description: 简易的数据库连接执行SQL语句管理器
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.2
 */
public class DBManager {
	// 数据库驱动
	public String driver = null;
	// 数据库地址
	public String connectionUrl = null;
	// 用户名
	public String userName = null;
	// 密码
	public String passWord = null;

	public Connection Conn;

	public Statement Stmt;

	/**
	 * 构造方法
	 *
	 * @param driver
	 *            数据库驱动
	 * @param connectionUrl
	 *            数据库地址
	 * @param userName
	 *            用户名
	 * @param passWord
	 *            密码
	 */
	public DBManager(final String driver, final String connectionUrl, final String userName, final String passWord) {
		this.driver = driver;
		this.connectionUrl = connectionUrl;
		this.userName = userName;
		this.passWord = passWord;
	}

	/**
	 * 创建连接
	 *
	 * @return 是否成功
	 */
	public boolean OpenConnection() {
		boolean mResult = true;
		try {
			Class.forName(driver);
			if ((userName == null) && (passWord == null)) {
				Conn = DriverManager.getConnection(connectionUrl);
			} else {
				Conn = DriverManager.getConnection(connectionUrl, userName, passWord);
			}

			Stmt = Conn.createStatement();
			mResult = true;
		} catch (final Exception e) {
			System.out.println(e.toString());
			mResult = false;
		}
		return (mResult);
	}

	/**
	 * 关闭数据库连接
	 */
	public void CloseConnection() {
		try {
			if (Stmt != null) {
				Stmt.close();
			}
			if (Stmt != null) {
				Stmt.close();
			}
		} catch (final Exception e) {
			System.out.println(e.toString());
		}
	}

	/**
	 * 查询数据
	 *
	 * @param sql
	 *            语句
	 * @return 查询结果
	 */
	public ResultSet ExecuteQuery(final String sql) {
		if (Stmt == null) {
			return null;
		}
		ResultSet result = null;
		try {
			result = Stmt.executeQuery(sql);
		} catch (final Exception e) {
			System.out.println(e.toString());
		}
		return (result);
	}

	/**
	 * 更新数据
	 *
	 * @param sql
	 *            语句
	 * @return 是否成功
	 */
	public int ExecuteUpdate(final String sql) {
		if (Stmt == null) {
			return -1;
		}
		int result = 0;
		try {
			result = Stmt.executeUpdate(sql);
		} catch (final Exception e) {
			System.out.println(e.toString());
		}
		return (result);
	}
}